package com.af.security.mgt.account.password.token;


import com.af.security.mgt.user.User;
import com.af.security.property.SecurityProperties;
import com.github.yitter.idgen.YitIdHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * @author : zhenyun.su
 * @since : 2019/6/25
 */

@Service
public class UserPasswordTokenService {
    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private UserPasswordTokenRepository userPasswordTokenRepository;

    @Transactional(readOnly = true)
    public UserPasswordToken findByToken(String token) {
        return userPasswordTokenRepository.findByToken(token);
    }

    @Transactional(readOnly = true)
    public UserPasswordToken findByToken(User user) {
        return userPasswordTokenRepository.findByUser(user);
    }

    @Transactional(rollbackFor = Exception.class)
    public UserPasswordToken createPasswordResetToken(User user) {
        String token = UUID.randomUUID().toString();
        UserPasswordToken userPasswordToken = new UserPasswordToken(token, user);
        userPasswordToken.setId(YitIdHelper.nextId());
        userPasswordToken.calculateExpiryDate(securityProperties.getTokenExpired());
        return userPasswordTokenRepository.save(userPasswordToken);
    }

    @Transactional(rollbackFor = Exception.class)
    public void disableToken(String token) {
        UserPasswordToken passwordToken= userPasswordTokenRepository.findByToken(token);
        if (passwordToken != null){
            passwordToken.setEnabled(false);
            userPasswordTokenRepository.save(passwordToken);
        }
    }
}
